package com.wuseguang.springcloud.service.impl;

import com.wuseguang.springcloud.dao.jdbc.OrderJdbc;
import com.wuseguang.springcloud.dao.repository.OrderRepository;
import com.wuseguang.springcloud.entity.Orders;
import com.wuseguang.springcloud.service.OrderService;
import com.wuseguang.springcloud.util.DateUtil;
import com.wuseguang.springcloud.util.Result;
import com.wuseguang.springcloud.util.UUIDGenerator;
import com.wuseguang.springcloud.wxpay.sdk.MyConfig;
import com.wuseguang.springcloud.wxpay.sdk.WXPay;
import com.wuseguang.springcloud.wxpay.sdk.WXPayConstants;
import com.wuseguang.springcloud.wxpay.sdk.WXPayUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 订单表 服务实现类
 * </p>
 *
 * @author
 * @since 2020-09-21
 */
@Service
public class OrderServiceImpl implements OrderService {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private OrderRepository orderRepository;

    @Autowired
    public OrderJdbc orderJdbc;

    @Override
    public Result parentsOrder(Integer commodityId, String userId) {
        logger.info("家长下订单");
        String sql = "select id,commodity_name,convert(commodity_price,decimal(10,2)) commodity_price," +
                "vip_or_not,month,convert(original_price,decimal(10,2)) original_price from " +
                "commodity where id = ?";
        Map<String, Object> map = orderJdbc.queryMap(sql, commodityId);
        logger.info("价格={}", map.get("commodity_price"));
        //创建订单实体
        Orders order = new Orders();
        //商户订单号确保唯一使用uuid
        order.setOutTradeNo(UUIDGenerator.getUUID());
        //购买用户id
        order.setUserId(Integer.valueOf(userId));
        //价格
        BigDecimal price = new BigDecimal(String.valueOf(map.get("commodity_price")));
        order.setPrice(price);
        //下单时间
        order.setOrderTime(new Date());
        //支付状态
        order.setTransactionStatus(0);
        //支付人
        order.setType(0);
        //原价
        order.setOriginalPrice(new BigDecimal(String.valueOf(map.get("original_price"))));
        //商品id
        order.setCommodityId(Integer.valueOf(map.get("id").toString()));
        //商品名称
        order.setCommodityName(map.get("commodity_name").toString());
        //失效时间
        order.setFailureTime(DateUtil.addMinutesTwo(3));

        try {
            orderRepository.save(order);
        } catch (Exception e) {
            logger.info("e", e);
            return null;
        }
        //查询用户的openid
        sql = "select open_id_one string from parent where id = ?";
        //用户的openid
        String openId = orderJdbc.queryString(sql, userId);
        //如果openid 为空就要重新登录，从新获取openid
        if (StringUtils.isEmpty(openId)) {
            return null;
        }

        //签名后的集合
        Map<String, String> data2 = new HashMap<>();

        try {
            logger.info("开始统一下单");

            //开始统一下单
            MyConfig config = new MyConfig();
            //正式
            WXPay wxpay = new WXPay(config);
            //下单信息
            Map<String, String> data = new HashMap<String, String>();
            //商品描述
            data.put("body", map.get("commodity_name").toString());
            //商户订单号
            data.put("out_trade_no", order.getOutTradeNo());
            //设备号，PC网页或公众号内支付可以传"WEB"
            data.put("device_info", "");
            //标价币种，默认人民币：CNY
            data.put("fee_type", "CNY");
            String total_fee = price.multiply(new BigDecimal(100)).setScale(0, BigDecimal.ROUND_UP).toString();
            logger.info("total_fee = {}", total_fee);
            //标价金额，单位为分，
            data.put("total_fee", total_fee);
            //APP和网页支付提交用户端ip，Native支付填调用微信支付API的机器IP
            //47.114.96.177 测试环境 47.107.234.68正式环境
            data.put("spbill_create_ip", "47.114.96.177");
            //异步接收微信支付结果通知的回调地址，通知url必须为外网可访问的url，不能携带参数。
            data.put("notify_url", "https://www.yuguozhijia.cn/management/wxpay/notify");
            //交易类型   JSAPI：公众号支付，NATIVE：扫码支付，APP：APP支付 此处指定为扫码支付
            data.put("trade_type", "JSAPI");
            //trade_type=NATIVE时（即扫码支付），此参数必传。此参数为二维码中包含的商品ID，商户自行定义。
            data.put("product_id", "");
            //交易类型为JSAPI 时openId必填
            data.put("openid", openId);

            //统一下单
            Map<String, String> resp = wxpay.unifiedOrder(data);
            logger.info("统一下单结果：" + resp);


            /**
             * 判断http成功且结果成功
             */
            if ("SUCCESS".equals(resp.get("return_code")) && "SUCCESS".equals(resp.get("result_code"))) {

                //取出下面的值
                data2.put("appId", resp.get("appid"));
                data2.put("timeStamp", Long.toString(WXPayUtil.getCurrentTimestamp()));
                data2.put("package", "prepay_id=" + resp.get("prepay_id"));//取出里面的预订单id
                data2.put("nonceStr", WXPayUtil.generateNonceStr());
                data2.put("signType", WXPayConstants.MD5);
                //重新加密并塞到data里
                data2.put("paySign", WXPayUtil.generateSignature(data2, config.getKey()));
            }


        } catch (Exception e) {
            e.printStackTrace();
        }


        return new Result(data2);
    }
}
